<template>
  <div class="container">
    <AsideTitle :headeline="slideTitle" :icon="icon"></AsideTitle>
    <el-card>
      <HeadSearch @showdialog="showdialog" @searchHotline="searchHotline" :queryInfo="queryInfo" :flag="false" @clear="handleClear"></HeadSearch>
      <!-- 表格区域 -->
      <el-table border stripe :data="tableData" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="轮播图片" prop="messageDetail" width="350px">
          <template slot-scope="scope">
            <img :src="baseUrl+scope.row.relativePath" class="imgslide" @click="preview(scope.row)" alt />
          </template>
        </el-table-column>
        <el-table-column label="文章标题" prop="title"></el-table-column>
        <el-table-column label="创建人" prop="founder"></el-table-column>
        <el-table-column label="创建时间" prop="creationTime"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" class="handlebtn" @click="editdialog(scope.row)">修改</el-button>
            <el-button class="handlebtn" type="danger" size="mini" icon="el-icon-delete" @click="delhotline(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <div class="pag">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="queryInfo.pageNum" :page-sizes="[3]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </el-card>
    <!-- 预览图片dialog -->
    <el-dialog title="预览" :visible.sync="previewDialog" width="50%">
      <img :src="imgSrc" style="width:100%" alt />
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="previewDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增轮播图dialog -->
    <el-dialog title="新增轮播图" :visible.sync="addDialog" width="35%">
      <span slot="footer" class="dialog-footer">
        <el-form ref="addSlideform" :model="addSlideform" label-width="80px">
          <el-form-item label="描述">
            <el-input v-model="addSlideform.desc"></el-input>
          </el-form-item>
          <el-form-item label="轮播图">
            <el-upload :limit="1" name="file" :action="serveUrl" list-type="picture-card" :on-remove="addhandleRemove" :on-success="handleSuccess" :on-error="handleFail" ref="upload">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!-- <el-dialog :visible.sync="imguploadvis">
                            <img width="100%" :src="updialogImageUrl" alt />
            </el-dialog>-->
          </el-form-item>
          <el-form-item label="文章标题">
            <el-select v-model="addSlideform.addArticeTitle" placeholder="请选择">
              <el-option v-for="item in addtitleOptions" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建者">
            <el-input v-model="addSlideform.author"></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" @click="FnaddDialog">确 定</el-button>
        <el-button @click="addDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改轮播图 -->
    <el-dialog title="修改轮播图" :visible.sync="editDialogvis" width="35%">
      <span slot="footer" class="dialog-footer">
        <el-form ref="editSlideform" :model="editSlideform" label-width="80px">
          <el-form-item label="描述">
            <el-input v-model="editSlideform.desc"></el-input>
          </el-form-item>
          <el-form-item label="轮播图">
            <el-upload :limit="limitnumber" :action="serveUrl" list-type="picture-card" :file-list="previewList" :on-remove="handleRemove" :on-success="handleEditSuccess" name="file" ref="editupload">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="文章标题">
            <el-select v-model="editSlideform.editArticleTitle" placeholder="请选择" @visible-change="seleChange">
              <el-option v-for="item in titleOptions" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建者">
            <el-input v-model="editSlideform.author"></el-input>
          </el-form-item>
        </el-form>

        <el-button type="primary" @click="FneditDialog" :disabled="flagslide">确 定</el-button>
        <el-button @click="ClearCache">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AsideTitle from "@/components/asideTitle";
import HeadSearch from "@/components/headSearch";
import global from "@/components/global";
export default {
  components: {
    AsideTitle,
    HeadSearch
  },
  data() {
    return {
      slideTitle: "轮播图管理",
      icon: "fa-window-restore",
      baseUrl: global.serverSrc,
      serveUrl: `${global.serverSrc}/carouse/uploadFile`, // upload上传地址
      //查询和分页参数
      queryInfo: {
        title: "",
        sourceInfo: "",
        pageNum: 1,
        pageSize: 5
      },

      tableData: [],
      addtitleOptions: [], //新增
      titleOptions: [], //标题选择数组
      total: 1,
      previewDialog: false, //预览图片
      imgSrc: "", //预览大图的路径

      addDialog: false, //新增轮播图
      //新增轮播图表单
      addSlideform: {
        desc: "",
        addArticeTitle: "",

        author: "",
        absolutePath: "",
        relativePath: ""
      },
      // addSlideform.addArticeTitle
      //编辑轮播图表单
      editSlideform: {
        desc: "",
        editArticleTitle: "",
        author: "",
        absolutePath: "",
        relativePath: ""
      },
      editDialogvis: false, //修改轮播图
      keyId: "", //主键id
      json: {},//获取数据,
      previewList: [{ name: '', url: '' }],
      limitnumber: 1,
      flagslide:false
    };
  },
  mounted() {
    this.getHotlineTableData();
    this.getArtileTitle()
  },

  methods: {
    //获取文章标题
    async getArtileTitle(type) {
      let res = await this._API.getNoticeList({ id: 0 });
      if (res && res.data.code == 0) {
        res = res.data.data
        console.log(res);
        res = res.map(e => {
          return { id: e.id, title: e.title };
        });
        if (type == "add") {
          this.addtitleOptions = res;
          console.log(this.addtitleOptions);
        } else {
          this.titleOptions = res;
          console.log(this.titleOptions);
        }
      }
      // list = list.map(e => {
      //     return { id: e.id, title: e.title };
      // });
    },
    //新增按钮
    showdialog() {
      this.addDialog = true;
      this.getArtileTitle("add");
    },
    //新增diolog图片上传成功钩子
    handleSuccess(file) {
      console.log(file);
      if (file.code == 0) {
        this.addSlideform.relativePath = file.data.relativePath;
        this.addSlideform.absolutePath = file.data.absolutePath;
      }
    },
    //新增dialog上传失败
    handleFail() {
      this.$message.error("图片上传失败");
    },
    //新增dialog删除图片
    addhandleRemove(file) {
      console.log(file);
    },

    //新增diolog 点击确定
    async FnaddDialog() {
      //判断数据是否为空
      if (this.addSlideform.desc == "") {
        this.$message.warning("轮播图描述不能为空");
        return false;
      }
      if (this.addSlideform.relativePath == "") {
        this.$message.warning("图片不能为空");
        return false;
      }
      if (this.addSlideform.addArticeTitle == "") {
        this.$message.warning("文章标题不能为空");
        return false;
      }
      if (this.addSlideform.author == "") {
        this.$message.warning("创建者不能为空");
        return false;
      }
      console.log(this.addSlideform);

      let { data: res } = await this._API.addCarousel({
        articleId: this.addSlideform.addArticeTitle,
        // title: this.addSlideform.addArticeTitle.title,
        description: this.addSlideform.desc,
        absolutePath: this.addSlideform.absolutePath,
        relativePath: this.addSlideform.relativePath,
        founder: this.addSlideform.author
      });
      console.log(res);
      if (res.code == 0) {
        this.$message.success("添加成功");

        this.getHotlineTableData();
        this.addSlideform = {

        };

        //editupload this.$refs.editupload.clearFiles();
      }

      this.addDialog = false;
    },
    // 清缓存
    ClearCache() {
      this.editDialogvis = false

    },
    //搜索按钮
    async searchHotline(query) {
      console.log(query);

      let jsonval = {
        title: query.title,
        founder: query.author,

        pageNum: this.queryInfo.pageNum,
        pageSize: this.queryInfo.pageSize
      };
      let { data: res } = await this._API.getCarousel(jsonval);
      if (res.code == 0) {
        console.log(11);

        this.tableData = res.data.list;
        this.total = res.data.total;
      }
    },

    //获取数据
    async getHotlineTableData() {
      let jsonquery = {
        title: this.queryInfo.title,
        founder: "",
        pageNum: this.queryInfo.pageNum,
        pageSize: this.queryInfo.pageSize
      };
      let { data: res } = await this._API.getCarousel(jsonquery);
      console.log(res);

      if (res.code == 0) {
        this.tableData = res.data.list;
        if (this.tableData.length >= 3) {
          this.tableData.length = 3;
          this.showdialog = () => {
            this.$message.warning("轮播图数据只能3条");
            this.addDialog = false;
          };
        } else {
          this.showdialog = () => {
            this.addDialog = true;
            this.getArtileTitle("add");
          };
        }
        this.total = res.data.total;
      }
    },

    //切换每页数据
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getHotlineTableData();
    },
    //切换到多少页
    handleCurrentChange(newNum) {
      console.log(newNum);

      this.queryInfo.pageNum = newNum;
      this.getHotlineTableData();
    },
    //点击删除按钮
    async delhotline(val) {
      let confirmResult = await this.$confirm(
        "此操作将永久删除该信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除！");
      }
      this.keyId = val.id;
      let { data: res } = await this._API.deleteCarousel({
        id: this.keyId,
        deleter: "deldefaule" //没写登录 默认值
      });

      if (res.code == 0) {
        this.$message.success("删除成功");
        this.getHotlineTableData();
      }
      this.$message.success("删除成功");
    },

    //点击图片预览
    preview(item) {
      this.previewDialog = true;
      this.imgSrc = this.baseUrl + "/" + item.relativePath;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    //编辑轮播图
    editdialog(item) {

      //this.editSlideform = item
      this.editDialogvis = true;
      console.log(item);
      this.keyId = item.id;
      //   if (this.previewList.length == 1) {
      //     this.previewList.length = 0

      //   }
      console.log(this.titleOptions);
      this.previewList[0].name = item.absolutePath
      this.previewList[0].url = this.baseUrl + item.relativePath
      // this.previewList.push({ name: item.absolutePath, url: this.baseUrl + item.relativePath })
      this.editSlideform.desc = item.description;
      this.editSlideform.author = item.founder;
      this.titleOptions.forEach(e => {
        if (e.id == item.articleId) {
          this.editSlideform.editArticleTitle = e.title
        }
      })
      // this.editSlideform.editArticleTitle = this.titleOptions[item.articleId].title
      this.editSlideform.relativePath = item.relativePath;
      this.editSlideform.absolutePath = item.absolutePath;
    },
    //编辑dialog上传成功的钩子
    handleEditSuccess(file) {
      if (file.code == 0) {
        this.editSlideform.relativePath = file.data.relativePath;
        this.editSlideform.absolutePath = file.data.absolutePath;
      }
    },
    //编辑diolog 点击确定
    async FneditDialog() {
      //判断数据是否为空
      console.log(this.editSlideform);

      if (this.editSlideform.desc == "") {
        this.$message.warning("轮播图描述不能为空");
        return false;
      }
      if (this.editSlideform.relativePath == "") {
        this.$message.warning("图片不能为空");
        return false;
      }
      if (this.editSlideform.editArticleTitle == "") {
        this.$message.warning("标题不能为空");
        return false;
      }
      if (this.editSlideform.author == "") {
        this.$message.warning("创建者不能为空");
        return false;
      }
      this.flagslide = true
      let { data: res } = await this._API.upCarousel({
        id: this.keyId,
        articleId: this.editSlideform.editArticleTitle,
        // title: this.editSlideform.editArticleTitle.title,
        description: this.editSlideform.desc,
        absolutePath: this.editSlideform.absolutePath,
        relativePath: this.editSlideform.relativePath,
        updater: this.editSlideform.author
      });
      console.log(res);
      if (res.code == 0 && res.state == 200) {
        this.flagslide = false
        this.$message.success("编辑成功");
        this.editSlideform.relativePath = ''
        this.editSlideform.absolutePath = ''

        this.getHotlineTableData();
      } else {
        this.$message.success("编辑失败"); 
        this.flagslide = false
      }
      console.log(this.$refs.editupload);


      this.editDialogvis = false;
    },
    //下拉触发的钩子
    seleChange() {
      if (this.keyId) {
        this.getArtileTitle();
      }
    },
    //取消搜索记录
    handleClear() {
      this.getHotlineTableData();
    }
  }
};
</script>

<style scoped lang="scss">
.pag {
  display: flex;
  justify-content: flex-end;
}
.imgslide {
  height: 100px;
  width: auto;
}

.el-form-item {
  text-align: left;
}
</style>